#include <iostream>
#include <queue>

using namespace std;


class Solution {
    public:
        long long countSubarrays_(vector<int>& nums, int minK, int maxK, int left, int right)
        {
            int n = right - left + 1;
            int ret = 0;
            bool min_s = false;
            bool max_s = false;
            for(int i = left; i< left + n; ++i)
            {
                for(int j = left + i; j < left + n - 1; ++j)
                {
                    if(nums[j] == minK)
                        min_s = true;   
                    if(nums[j] == maxK)
                        max_s = true;
                    if(min_s || max_s)
                        ret += (right - j) + 1;
                }
            }
            return ret;
        }
    
        long long countSubarrays(vector<int>& nums, int minK, int maxK) {
            queue<int> q;
            q.push(0);
            int n = nums.size();
            int i = 0;
            while(i < n)
            {
                if(nums[i] < minK || nums[i] > maxK)
                {
                    q.push(i-1);
                    while(i < n && (nums[i] < minK || nums[i] > maxK))
                    {
                        ++i;
                    }
                    if(i < n)
                        q.push(i);
                }
                ++i;
            }
    
            long long sum = 0;
            while(!q.empty())
            {
                int left = q.front();
                q.pop();
                int right = q.front();
                q.pop();
                sum += countSubarrays_(nums, minK, maxK, left, right);
            }
            return sum;
        }
    };